// 535. TinyURL 的加密与解密
/**
 * 自增
 *  encode 函数
 *  使用自增 id 作为longUrl的键，每接收一个longUrl都将id加1,将键值
 *  (id,longUrl) 插入数据库dataBase 然乎返回带有id的字符串作为shorUrl
 *
 *  Decode 函数
 *  将shortUrl转换成对于的 key,然后在对于的dataBase中查找对应的key对应的longUrl
 * */

var encode = function (longUrl) {
	this.dataStore = new Map()
	this.id = 0
	this.id++
	this.dataStore.set(this.id, longUrl)
	return 'http://tinyurl.com/' + this.id
}
// 随机数
var encode = function (longUrl) {
	this.dataStore = new Map()
	let key
	while (true) {
		key = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
		if (!this.dataStore.has(key)) break
	}
	this.dataStore.set(key, longUrl)
	return 'http://tinyurl.com/' + key
}

// 哈希生成
var encode = function (longUrl) {
	/* 选择两个合适的质数 */
	const K1 = 1117
	const K2 = 10 ** 9 + 7
	this.dataStore = new Map()
	this.urlTokey = new Map()
	if (this.urlTokey.has(longUrl)) {
		return 'http://tinyurl.com/' + this.urlTokey.get(longUrl)
	}
	let key = 0
	let base = 1
	for (let i = 0; i < longUrl.length; i++) {
		const c = longUrl[i].charCodeAt(0)
		key = (key + c * base) % K2
		base = (base * K1) % K2
	}

	while (this.dataStore.has(key)) {
		key = (key + 1) % K2
	}
	this.dataStore.set(key, longUrl)
	this.urlTokey.set(longUrl, key)
	return 'http://tinyurl.com/' + key
}
var decode = function (shortUrl) {
	const p = shortUrl.lastIndexOf('/') + 1
	const key = parseInt(shortUrl.substring(p))
	return this.dataStore.get(key)
}
